import { BzUser } from '@/lib/models';
import { createContext, PropsWithChildren, useContext, useState } from 'react';

const AuthContext = createContext<
  | {
      user: BzUser | null;
      logIn: (user: BzUser) => void;
      logOut: () => void;
    }
  | undefined
>(undefined);

function AuthProvider({ children }: PropsWithChildren) {
  const [user, setUser] = useState<BzUser | null>(null);

  return (
    <AuthContext.Provider
      value={{
        user,
        logIn: (user: BzUser) => setUser(user),
        logOut: () => setUser(null),
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within a AuthProvider');
  }
  return context;
}

export { AuthProvider, useAuth };
